package com.xiaobai.common.utils.tool;


import com.xiaobai.common.utils.TokenUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Objects;

public class AuthUtil {
    private static final String TOKEN = "token";
    private static final String ID = "id";
    private static final String DEPT = "deptId";
    private static final String ROLE = "roleId";
    private static final String SESSIONID = "sessionId";

    public static String getToken(HttpServletRequest request) {
        return request.getHeader(TOKEN);
    }

    public static String getToken() {
        HttpServletRequest request = WebUtil.getRequest();
        if (Objects.isNull(request)) {
            return null;
        }
        return getToken(request);
    }

    public static String getSessionId() {
        HttpServletRequest request = WebUtil.getRequest();
        if (Objects.isNull(request)) {
            return null;
        }
        return getSessionId(request);
    }

    public static String getSessionId(HttpServletRequest request) {
        return request.getHeader(SESSIONID);
    }

    public static UserInfo getUser(HttpServletRequest request) {
        String token = getToken(request);
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        Claims claims = TokenUtil.parseClaims(token);
        if (StringUtils.isEmpty(claims)) {
            return null;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setId(Long.valueOf(Func.toStr(claims.get(ID))))
            .setDeptId(Func.toStr(claims.get(DEPT)))
            .setRoleId(Func.toStr(claims.get(ROLE)));
        return userInfo;
    }

    public static UserInfo getUser() {
        HttpServletRequest request = WebUtil.getRequest();
        if (Func.isEmpty(request)) {
            return null;
        }
        return getUser(request);
    }

    public static Long getId() {
        UserInfo user = getUser();
        return null == user ? null : user.getId();
    }

    public static Long getId(HttpServletRequest request) {
        UserInfo user = getUser(request);
        return null == user ? null : user.getId();
    }

    public static String getDept() {
        UserInfo user = getUser();
        return null == user ? null : user.getDeptId();
    }

    public static String getDept(HttpServletRequest request) {
        UserInfo user = getUser(request);
        return null == user ? null : user.getDeptId();
    }

    public static String getRole() {
        UserInfo user = getUser();
        return null == user ? null : user.getRoleId();
    }

    public static String getRole(HttpServletRequest request) {
        UserInfo user = getUser(request);
        return null == user ? null : user.getRoleId();
    }

}
